<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => '未登录']);
    exit;
}

$user_id = $_SESSION['user_id'];
$amount = floatval($_POST['amount'] ?? 0);
$withdraw_method = $_POST['withdraw_method'] ?? '';
$account = trim($_POST['account'] ?? '');

try {
    // 验证输入
    if ($amount <= 0) {
        throw new Exception('提现金额必须大于0');
    }
    
    if (empty($withdraw_method)) {
        throw new Exception('请选择提现方式');
    }
    
    if (empty($account)) {
        throw new Exception('请输入收款账号');
    }
    
    // 最低提现金额
    if ($amount < 1) {
        throw new Exception('最低提现金额为¥1');
    }
    
    // 获取用户当前余额
    $user_balance = getUserBalance($user_id);
    
    if ($amount > $user_balance) {
        throw new Exception('余额不足，当前可提现余额: ¥' . number_format($user_balance, 2));
    }
    
    // 计算阶梯式手续费
    if ($amount < 100) {
        $fee_rate = 0.15; // 小于100，15%手续费
    } elseif ($amount < 500) {
        $fee_rate = 0.10; // 100-500之间，10%手续费
    } else {
        $fee_rate = 0.05; // 大于500，5%手续费
    }
    
    $fee = $amount * $fee_rate;
    $actual_amount = $amount - $fee;
    
    // 创建提现记录表（如果不存在）
    $create_table_sql = "
        CREATE TABLE IF NOT EXISTS withdraw_records (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            amount DECIMAL(10,2) NOT NULL,
            fee DECIMAL(10,2) NOT NULL,
            actual_amount DECIMAL(10,2) NOT NULL,
            withdraw_method VARCHAR(50) NOT NULL,
            account VARCHAR(255) NOT NULL,
            status ENUM('pending', 'processing', 'completed', 'rejected') DEFAULT 'pending',
            admin_note TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            processed_at TIMESTAMP NULL,
            INDEX idx_user_id (user_id),
            INDEX idx_status (status)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ";
    
    try {
        $pdo->exec($create_table_sql);
    } catch (PDOException $e) {
        // 表可能已存在，忽略错误
    }
    
    $pdo->beginTransaction();
    
    // 扣除用户余额
    $stmt = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
    $stmt->execute([$amount, $user_id]);
    
    // 记录提现申请
    $stmt = $pdo->prepare("
        INSERT INTO withdraw_records (user_id, amount, fee, actual_amount, withdraw_method, account, status, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW())
    ");
    $stmt->execute([$user_id, $amount, $fee, $actual_amount, $withdraw_method, $account]);
    
    $pdo->commit();
    
    // 记录日志
    error_log("用户 {$user_id} 提现申请: ¥{$amount}, 手续费: ¥{$fee}, 实际金额: ¥{$actual_amount}, 方式: {$withdraw_method}");
    
    echo json_encode([
        'success' => true,
        'message' => '提现申请提交成功',
        'amount' => $amount,
        'fee' => $fee,
        'actual_amount' => $actual_amount
    ]);
    
} catch (Exception $e) {
    $pdo->rollBack();
    
    // 记录错误日志
    error_log("提现失败 - 用户: {$user_id}, 金额: {$amount}, 错误: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
